﻿using B.S.BasicData.API.Read.Application.Command.Menu;
using B.S.BasicData.API.Read.DTOS.UserRoleMenu;
using B.S.BasicData.Domain.Entities.UserRoleMenu;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.API.Read.Application.Handler.Menu
{
    /// <summary>
    /// 获取菜单信息请求命令处理类
    /// </summary>
    public class GetMenuHandler:IRequestHandler<GetMenuCommand,ApiResult<List<MenuDTO>>>
    {
        IBaseRepository<MenuModel> menuRep;

        public GetMenuHandler(IBaseRepository<MenuModel> menuRep)
        {
            this.menuRep = menuRep;
        }

        public Task<ApiResult<List<MenuDTO>>> Handle(GetMenuCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<List<MenuDTO>> res = new ApiResult<List<MenuDTO>>();

                var menus = menuRep.GetAll().OrderByDescending(x=>x.PaiXu).Where(x => !x.IsDeleted);
                var menups = menuRep.GetAll().OrderByDescending(x => x.PaiXu).Where(x => !x.IsDeleted);

                var linq = from a in menus
                           join b in menups on a.P_ID equals b.Id into ab
                           from b in ab.DefaultIfEmpty()
                           select new MenuDTO
                           {
                              Id=a.Id,
                              MenuName=a.MenuName,
                              Url=a.Url,
                              P_ID=a.P_ID,
                              PaiXu=a.PaiXu,
                              CreateName=a.CreateName,
                              CreateDate=a.CreateDate,
                              UpdateName=a.UpdateName,
                              UpdateDate= a.UpdateDate,
                              PName=b.MenuName
                           };
                res.Msg = "获取菜单信息";
                res.Code = ApiEnum.Success;
                res.Data=linq.ToList();
                return Task.FromResult(res);

            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
